home *** CD-ROM | disk | FTP | other *** search
/ MacFormat 1994 August / August CD.bin / Shareware / Education / numericalmethods Folder / chap_2 / a2_2.m < prev    next >
Encoding:
Text File  |  1994-06-05  |  2.0 KB  |  87 lines  |  [MATS/MATL]

  1. echo off;
  2. % NUMERICAL METHODS: MATLAB Programs, (c) John H. Mathews 1994
  3. % To accompany the text:
  4. % NUMERICAL METHODS for Mathematics, Science and Engineering, 2nd Ed, 1992
  5. % Prentice Hall, Englewood Cliffs, New Jersey, 07632, U.S.A.
  6. % This free software is complements of the author.
  7.  
  8. % Algorithm 2.2 (Bisection Method).
  9. % Section    2.2,    Bracketing Methods for Locating a Root, Page 61
  10. echo on; clc; format long; hold off; clear
  11.  
  12. % This program implements the bisection method.
  13.  
  14. %    Define and store f(x) in the M-file  f.m
  15. % function y = f(x)
  16. % y = x.*sin(x) - 1;
  17.  
  18. delete f.m
  19. diary f.m; disp('function y = f(x)');...
  20.            disp('y = x.*sin(x) - 1;');...
  21. diary off;
  22.  
  23. % Remark. f.m and bisect.m are used for Algorithm 2.2
  24. f(0); % Test for file f.m
  25. pause    % Press any key to see the graph y = f(x).
  26.  
  27. clc; clg;
  28. a = 0;
  29. b = 2;
  30. c = -1;
  31. d = 1;
  32. h = (b-a)/150;
  33. X = a:h:b;
  34. Y = f(X);
  35. axis([a b c d]);...
  36. plot(X,Y,'-g');...
  37. hold on;...
  38. plot([a b],[0 0],'b',[0 0],[c d],'b');...
  39. xlabel('x');...
  40. ylabel('y');...
  41. title('Graph of y = f(x).');...
  42. grid;...
  43. axis;...
  44. hold off;...
  45. shg; pause    % Press any key to continue.
  46.  
  47. clc;
  48. %    Place the starting endpoints for [a,b] in  a  and  b
  49.  
  50. %    Place the tolerance in  delta
  51.  
  52. a = 0;  
  53. b = 2;  
  54. delta = 1e-6;
  55.  
  56. [p,yp,err,P] = bisect('f',a,b,delta);
  57.  
  58. pause    % Press any key for the list of iterations.
  59.  
  60. clc; clg;
  61. [m1 m2] = size(P);
  62. n0 = min(7,m1);
  63. Xc = (P(1:n0,1)+P(1:n0,2))'/2;
  64. X0 = [a,Xc,b];
  65. Z0 = zeros(1,n0+2);
  66. axis([a b c d]);...
  67. plot(X,Y,'-g',X0,Z0,'or');...
  68. hold on;...
  69. plot([a b],[0 0],'b',[0 0],[c d],'b');...
  70. xlabel('x');...
  71. ylabel('y');...
  72. title('Graphical analysis for the bisection method.');...
  73. grid;...
  74. axis;
  75. hold off;...
  76. shg; pause    % Press any key to continue.
  77.  
  78. Mx1 = 'Iterations for the bisection method.';
  79. Mx2 = '     a                  b';
  80. Mx3 = 'The approximate root is:';
  81. Mx4 = 'The error estimate for p is  ± ';
  82. clc,echo off, diary output,...
  83. disp(''),disp(Mx1),disp(''),disp(Mx2),disp(P),...
  84. disp(''),disp(Mx3),disp(''),disp('p = '),disp(p),...
  85. disp('f(p) = '),disp(yp),disp(''),...
  86. disp([Mx4,num2str(err)]),diary off, echo on
  87.